package com.j2110.controller;

import com.j2110.pojo.User;
import com.j2110.service.UserService;
import com.j2110.utils.Result;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    //登录
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据
        Map<String, String[]> map = req.getParameterMap();
        //封装数据
        User u = new User();
        try {
            BeanUtils.populate(u,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取验证码
        String rc = (String) req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
        //获取登录数据的结果集
        Result result = new UserService().login(u);

        if (rc.equalsIgnoreCase(u.getCode())) {
            //验证码正确
            if (result.isSuccess()){
                req.getSession().setAttribute("LOGIN_NAME",u.getUsername());
                resp.sendRedirect( req.getContextPath() + "/emp/index");
            }else {
                req.getSession().setAttribute("msg", result.getMsg());
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }else {
            req.getSession().setAttribute("msg", "验证码错误");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清除session
        req.getSession().removeAttribute("LOGIN_NAME");
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}
